#!/bin/bash

# 解析命令行参数
usage() {
    echo "用法: $0 [选项]"
    echo "选项:"
    echo "  -p, --path PATH    指定安装路径前缀 (比如: ./install.sh -p /usr/local/bin)"
    echo "  -h, --help         显示此帮助信息"
    exit 1
}

# 默认安装路径
CUSTOM_INSTALL_PATH=""

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    key="$1"
    case $key in
        -p|--path)
            CUSTOM_INSTALL_PATH="$2"
            shift 2
            ;;
        -h|--help)
            usage
            ;;
        *)
            echo "未知选项: $1"
            usage
            ;;
    esac
done

# 导出安装路径环境变量，供config.sh使用
export CUSTOM_INSTALL_PATH

# 检查是否提供了安装路径
if [ -z "$CUSTOM_INSTALL_PATH" ]; then
    echo "错误: 必须指定安装路径"
    usage
fi

# 加载配置
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "${SCRIPT_DIR}/service/config.sh"

# 显示安装信息
info "安装路径: ${INSTALL_FULL_PATH}"

# 设置备份相关变量（这些在config.sh中没有）
DATETIME=$(date +%Y%m%d_%H%M%S)
BACKUP_ROOT="${INSTALL_PATH}/fdsmastergo_backup"
BACKUP_FILE="${BACKUP_ROOT}/${SOFTWARE_NAME}_${DATETIME}.tar.gz"

# 检查权限
check_root

# 提示用户安装影响
echo -e "${YELLOW}警告：${NC}"
echo "1. 安装过程将会停止所有 ${SOFTWARE_NAME} 服务"
echo "2. 安装过程预计需要 1-3 分钟"
echo "3. 旧版本将被备份到 ${BACKUP_FILE}"
echo -e "${YELLOW}是否继续？[y/N]${NC}"
read -r response
if [[ ! "$response" =~ ^[yY]$ ]]; then
    echo "安装已取消"
    exit 0
fi

# 停止现有服务
info "停止现有服务..."
if [ -f "${INSTALL_FULL_PATH}/service/micro_stop.sh" ]; then
    "${INSTALL_FULL_PATH}/service/micro_stop.sh"
else
    warn "未找到停止脚本: ${INSTALL_FULL_PATH}/service/micro_stop.sh"
fi

# 备份和清理
if [ -d "${INSTALL_FULL_PATH}" ]; then
    # 创建备份目录
    mkdir -p "${BACKUP_ROOT}"
    
    warn "备份旧版本到 ${BACKUP_FILE}..."
    # 备份（使用tar压缩）
    tar -czf "${BACKUP_FILE}" -C "$(dirname "${INSTALL_FULL_PATH}")" "$(basename "${INSTALL_FULL_PATH}")" || error "备份失败"
    # 清理旧版本
    info "清理旧版本..."
    rm -rf "${INSTALL_FULL_PATH}"
else
    # 创建新目录
    mkdir -p "${INSTALL_FULL_PATH}" || error "创建目录失败"
fi

# 创建目标目录
info "开始安装 ${SOFTWARE_NAME}..."

# 获取当前目录（应该是fdsmastergo_install目录）
CURRENT_DIR="$( pwd )"

# 复制文件
info "正在复制文件..."
info "源目录: ${CURRENT_DIR}"

info "复制可执行文件..."
cp -r "${CURRENT_DIR}/cmd" "${INSTALL_FULL_PATH}/" || error "复制可执行文件失败"
info "复制服务脚本..."
cp -r "${CURRENT_DIR}/service" "${INSTALL_FULL_PATH}/" || error "复制服务脚本失败"
info "复制卸载脚本..."
cp "${CURRENT_DIR}/uninstall.sh" "${INSTALL_FULL_PATH}/" || error "复制卸载脚本失败"
info "复制说明文档..."
cp "${CURRENT_DIR}/README.md" "${INSTALL_FULL_PATH}/" || error "复制说明文档失败"
info "复制配置文件..."
cp "${CURRENT_DIR}/services.json" "${INSTALL_FULL_PATH}/" || error "复制配置文件失败"

# 设置权限
info "设置文件权限..."
chmod -R 755 "${INSTALL_FULL_PATH}/cmd"
chmod -R 755 "${INSTALL_FULL_PATH}/service"
chmod 644 "${INSTALL_FULL_PATH}/services.json"
chmod 755 "${INSTALL_FULL_PATH}/uninstall.sh"
chmod 644 "${INSTALL_FULL_PATH}/README.md"

# 安装环境变量配置
info "安装环境变量配置..."
if [ -f "${CURRENT_DIR}/fdsmastergo_evn.sh" ]; then
    # 创建临时环境变量配置文件
    TMP_ENV_FILE="/tmp/fdsmastergo_evn.sh.tmp"
    cp "${CURRENT_DIR}/fdsmastergo_evn.sh" "${TMP_ENV_FILE}"
    
    # 替换安装路径
    sed -i "s|__INSTALL_FULL_PATH__|${INSTALL_FULL_PATH}|g" "${TMP_ENV_FILE}"
    
    # 复制修改后的环境变量配置文件
    cp "${TMP_ENV_FILE}" "/etc/profile.d/fdsmastergo_evn.sh" || error "复制环境变量配置文件失败"
    chmod 644 "/etc/profile.d/fdsmastergo_evn.sh" || error "设置环境变量配置文件权限失败"
    info "环境变量配置安装成功"
    
    # 清理临时文件
    rm -f "${TMP_ENV_FILE}"
    
    # 复制到安装目录
    cp "${CURRENT_DIR}/fdsmastergo_evn.sh" "${INSTALL_FULL_PATH}/service/" || error "复制环境变量配置文件到安装目录失败"
    sed -i "s|__INSTALL_FULL_PATH__|${INSTALL_FULL_PATH}|g" "${INSTALL_FULL_PATH}/service/fdsmastergo_evn.sh"
else
    error "未找到环境变量配置文件: ${CURRENT_DIR}/fdsmastergo_evn.sh"
fi

# 安装开机启动脚本
info "安装开机启动脚本..."
if [ -f "${INSTALL_FULL_PATH}/service/fdsmastergo" ]; then
    cp "${INSTALL_FULL_PATH}/service/fdsmastergo" "/etc/init.d/fdsmastergo" || error "复制启动脚本失败"
    chmod 755 "/etc/init.d/fdsmastergo" || error "设置启动脚本权限失败"
    if command -v update-rc.d >/dev/null 2>&1; then
        update-rc.d fdsmastergo defaults || warn "设置开机启动失败(update-rc.d)"
    elif command -v chkconfig >/dev/null 2>&1; then
        chkconfig --add fdsmastergo || warn "设置开机启动失败(chkconfig)"
    else
        warn "未找到update-rc.d或chkconfig，请手动设置开机启动"
    fi
    info "开机启动脚本安装成功"
else
    error "未找到启动脚本: ${INSTALL_FULL_PATH}/service/fdsmastergo"
fi

# 启动服务
info "启动服务..."
"${INSTALL_FULL_PATH}/service/micro_start.sh"
status=$?

# 检查服务状态
info "检查服务状态..."
"${INSTALL_FULL_PATH}/service/micro_status.sh"

# 安装完成
echo
echo -e "${GREEN}安装完成！${NC}"
echo -e "${YELLOW}安装信息：${NC}"
echo -e "  安装路径：${INSTALL_FULL_PATH}"
echo -e "  备份文件：${BACKUP_FILE}"
echo -e "  可执行文件：${INSTALL_FULL_PATH}/cmd/*/bin/*"
echo -e "  配置文件：${INSTALL_FULL_PATH}/services.json"
echo -e "  环境变量：/etc/profile.d/fdsmastergo_evn.sh"
echo
echo -e "${YELLOW}使用说明：${NC}"
echo -e "  1. 加载环境变量："
echo -e "     source /etc/profile"
echo -e "  2. 服务管理："
echo -e "     - 启动服务：fdsmastergo-start"
echo -e "     - 停止服务：fdsmastergo-stop"
echo -e "     - 重启服务：fdsmastergo-restart"
echo -e "     - 查看状态：fdsmastergo-status"
echo -e "  3. 查看日志："
echo -e "     - 查看所有日志：fdsmastergo-log"
echo -e "     - 查看具体服务日志：tail -f ${INSTALL_FULL_PATH}/logs/服务名称/*.log"
echo

echo -e "${YELLOW}卸载说明：${NC}"
echo -e "  1. 如需卸载，请执行："
echo -e "     cd ${INSTALL_FULL_PATH} && ./uninstall.sh"
echo -e "  2. 重要提示："
echo -e "     - 不同版本的卸载脚本可能不兼容，安装和卸载程序的版本要一致"
echo -e "     - 禁止使用新版本的卸载脚本来卸载旧版本程序"
echo

echo -e "${YELLOW}备份说明：${NC}"
echo -e "  1. 旧版本已备份到：${BACKUP_FILE}"
echo -e "  2. 如需回滚，请按以下步骤操作："
echo -e "     a) 停止当前服务：fdsmastergo-stop"
echo -e "     b) 删除当前安装：rm -rf ${INSTALL_FULL_PATH}/*"
echo -e "     c) 解压备份文件：tar -xzf ${BACKUP_FILE} -C $(dirname "${INSTALL_FULL_PATH}")"
echo -e "     d) 重新加载环境变量：source /etc/profile"
echo -e "     e) 启动服务：fdsmastergo-start"
echo
echo -e "${GREEN}祝您使用愉快！${NC}"

echo -e "${YELLOW}相关信息也可参考 ${INSTALL_FULL_PATH}/README.md ${NC}"

exit $status
